import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { message } from 'ant-design-vue';
import MainLayout from '@/layouts/MainLayout.vue';
import FullWidthLayout from '@/layouts/FullWidthLayout.vue';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/info',
    name: 'Info',
    component: () => import('@/views/info/info.vue')
  },
  {
    path: '/',
    component: MainLayout,
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('@/views/Home.vue')
      },
      {
        path: 'article/:id',
        name: 'ArticleDetail',
        component: () => import('@/views/ArticleDetail.vue')
      },
      {
        path: 'category/:id',
        name: 'Category',
        component: () => import('@/views/Category.vue')
      },

    ]
  },
  {
    path: '/timeline',
    component: FullWidthLayout,
    children: [
      {
        path: '',
        name: 'Timeline',
        component: () => import('@/views/TimelinePage.vue')
      }
    ]
  },
  {
    path: '/user',
    component: () => import('@/layouts/UserLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: 'profile',
        name: 'UserProfile',
        component: () => import('@/views/user/Profile.vue')
      },
      {
        path: 'articles',
        name: 'UserArticles',
        component: () => import('@/views/user/Articles.vue')
      },
      {
        path: 'settings',
        name: 'UserSettings',
        component: () => import('@/views/user/Settings.vue')
      },
      {
        path: 'article/edit',
        name: 'ArticleCreate',
        component: () => import('@/views/user/ArticleEdit.vue')
      },
      {
        path: 'article/edit/:id',
        name: 'ArticleEdit',
        component: () => import('@/views/user/ArticleEdit.vue')
      }
    ]
  },
  // {
  //   path: '/login',
  //   name: 'Login',
  //   component: () => import('@/views/auth/Login.vue'),
  //   meta: { guestOnly: true }
  // },
  // {
  //   path: '/register',
  //   name: 'Register',
  //   component: () => import('@/views/auth/Register.vue'),
  //   meta: { guestOnly: true }
  // }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  
  // 检查用户是否已登录
  const isLoggedIn = userStore.checkLogin();
  
  // 需要登录的路由
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isLoggedIn) {
      message.warning('请先登录');
      next({ name: 'Login', query: { redirect: to.fullPath } });
      return;
    }
  }
  
  // 只允许未登录用户访问的路由（如登录页）
  if (to.matched.some(record => record.meta.guestOnly)) {
    if (isLoggedIn) {
      next({ name: 'Home' });
      return;
    }
  }
  
  next();
});

export default router; 